package com.nbicc.parent.interceptor;

import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import java.util.Set;

/**
 * Created by li on 17/12/25.
 * 自定义路径拦截规则接口
 */
public abstract class BaseInterceptorRegulation implements HandlerInterceptor {

    /**
     * 是否激活此拦截器
     */
    protected boolean isenabled = true;

    /**
     * 需要拦截的路径
     * @return
     */
    protected Set<String> getIncludePatterns(){return null;}

    /**
     * 非拦截路径
     * @return
     */
    protected Set<String> getExcludePatterns(){return null;}

    /**
     * 路径正则表达式
     * @return
     */
    protected PathMatcher getPathMatcher(){return null;}

    /**
     * 注册拦截规则
     * @param registry
     * @return
     */
    public InterceptorRegistration addIntoRegistry(InterceptorRegistry registry){
        if(isenabled){
            InterceptorRegistration interceptorRegistration = registry.addInterceptor(this);
            if(getIncludePatterns() != null){
                for(String pathPattern : getIncludePatterns()){
                    interceptorRegistration.addPathPatterns(pathPattern);
                }
            }
            if(getExcludePatterns() != null){
                for(String pathPattern : getExcludePatterns()){
                    interceptorRegistration.excludePathPatterns(pathPattern);
                }
            }
            if(getPathMatcher() != null){
                interceptorRegistration.pathMatcher(getPathMatcher());
            }
            return interceptorRegistration;
        }
        return null;
    }
}
